const Base = require(think.APP_PATH + '/controller/base.js');
const nodemailer = require('nodemailer');
const str = Math.random().toString(36).substr(2);
const time = new Date().getTime();

module.exports = class extends Base {
    async indexAction() {

        let error;

        const field = {
            verify_id: await think.$tools.getMd5(str + time + Math.random()),
            email: this.ctx.state.data.data.email,
            emailCode: Math.random() * 100000000 | 0
        };

        const mailOptions = {
            from: 'postmaster <postmaster@admin.com>',//发件人地址
            to: field.email,
            subject: 'postmaster',//主题
            html: `<p>${field.emailCode}</p>`
        };

        const transporter = nodemailer.createTransport({
            host: 'email-smtp.us-west-2.amazonaws.com',//smtp服务器地址
            port: 465,//端口
            secure: true,//如果是加密的端口为true,否则false
            auth: {
                user: 'postmaster',//登陆smtp服务器的账号
                pass: 'postmaster'//登陆smtp服务器的密码
            }
        });

        try {
            await transporter.sendMail(mailOptions);
            this.model('verify/verify').addMailcode(field);
        } catch (err) {
            error = err.message
        }

        this.ctx.state.result = error || {verify_id: field.verify_id};

    };
};